<?php
require_once 'UserPermissionCategoryLink.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_UserPermissionCategoryLinks extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_user_permission_category_link';
}


/**
 *  
 */
class UserPermissionCategoryLinks extends BaseMapper
{
    protected $_modelName   = 'UserPermissionCategoryLink';
    protected $_dbTableName = 'Application_Model_DbTable_UserPermissionCategoryLinks';

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add 
     */
    public function addUserPermissionCategoryLink( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update 
     */
    public function updateUserPermissionCategoryLink( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  delete
     */
    public function deleteUserPermissionCategoryLinkByUserId( $userId )
    {
        $userId = (int) $userId;
        return $this->_delete( Array('user_id'=>$userId) );
    }

    /**
     *  find many 
     */
    public function findUserPermissionCategoryLinks( $id=null, $userId=null, $categoryId=null, $page=NULL, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            'id'            => $id,
            'userId'        => $userId,
            'categoryId'    => $categoryId,
            '_orderBy'      => ' id DESC ',
            '_page'         => $page,
            '_rowCount'     => $rowCount,
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get count by "findUserPermissionCategoryLinks" method
     */
    public function getNumFindUserPermissionCategoryLinks( $userId=-1, $categoryId=-1 ) 
    {
        $opt = Array(
            'id'           => $id,
            'userId'       => $userId,
            'categoryId'   => $categoryId,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'id'                   => (isset($opt['id'])                   ? (int) ($opt['id'])                   : NULL ),
            'userId'               => (isset($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'categoryId'           => (isset($opt['categoryId'])           ? (int) ($opt['categoryId'])           : NULL ),

            '_orderBy'             => (isset($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' id DESC ' ),
            '_page'                => (isset($opt['_page'])                ? (int) ($opt['_page'])                : NULL ),
            '_rowCount'            => (isset($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_orderBy']) ) {
            $opt['_orderBy'] = explode(',',$opt['_orderBy']);
        }

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '             , $opt['userId']               );  }
        if(isset( $opt['categoryId']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' category_id = ? '         , $opt['categoryId']           );  }

        // where from array to string
        $whereString = join(' AND ',$where);
        if(!$whereString) {
            $whereString = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($whereString) {
                $select->where( $whereString );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo $whereString;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {
        $model = $this->getModel();
        $model->setId         ( $row['id']          );
        $model->setUserId     ( $row['user_id']     );
        $model->setCategoryId ( $row['category_id'] );
        return $model;
    }

}

